// HelloWorld.Vue
<template>
  <!-- {{ rawData }} -->
  <!-- {{ winSize }} -->
  <!-- <el-button @click="test">test</el-button> -->
  <div class="chart" ref="chart"></div>
</template>
<script>
import { bus } from '@/main.js';
// 引入 ECharts 主模块
import { mapState, mapMutations } from 'vuex';
import * as echarts from 'echarts';

import { option } from './optsKLine.js';
let _configOpts = option;

export default {
  name: 'HelloWorld',
  components: {},
  props: {
    stock: {
      type: [String],
      validator: function(value) {
        let re = new RegExp(/^\d{4,6}\.[A-Z]{2,3}$/);
        return re.test(value);
      },
    },
  },
  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      rawData: [],
      optsEcharts: null,
      myChart: null,
      option: {},
    };
  },
  computed: {
    ...mapState(['winSize']),

    params_code: function() {
      let p = {
        get_type: 'range',
        prod_code: this.stock,
        candle_period: 6,
        // fields
        search_direction: 2,
        data_count: 300,
        start_date: this.$moment()
          .subtract(1, 'years')
          .format('YYYYMMDD'),
        end_date: this.$moment().format('YYYYMMDD'),
      };
      return p;
    },
    dates: function() {
      return this.rawData.map((item) => {
        return item[0];
      });
    },
    data: function() {
      return this.rawData.map(function(item) {
        return [item[1], item[4], item[2], item[3]];
      });
    },
  },
  methods: {
    test: function() {
      // console.log(this.$api);
      let p = this.params_code;
      this.$api
        .getKline(p)
        .then((res) => {
          let key = p.prod_code;
          let data = this._.get(res, 'data.candle')[key];
          this.rawData.splice(0, this.rawData.length);
          this.rawData.push(...data);
          return Promise.resolve(200);
        })
        .then((res) => {
          this.initChart();
        })
        .catch((err) => {
          console.error(err);
        })
        .finally((_) => {});
    },
    calculateMA: function(dayCount, data) {
      var result = [];
      for (var i = 0, len = data.length; i < len; i++) {
        if (i < dayCount) {
          result.push('-');
          continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
          sum += data[i - j][1];
        }
        result.push((sum / dayCount).toFixed(2));
      }
      return result;
    },
    initChart() {
      // 基于准备好的dom，初始化echarts实例
      this.myChart = echarts.init(this.$refs.chart);
      // 指定图表的配置项和数据

      let option = Object.assign(_configOpts, {});
      option.xAxis.data = this.dates;
      option.grid.bottom = this.$store.getters['getPXbyVW'](10);
      option.series[0].data = this.data;
      option.series[1].data = this.calculateMA(5, this.data);
      option.series[2].data = this.calculateMA(10, this.data);
      option.series[3].data = this.calculateMA(20, this.data);
      option.series[4].data = this.calculateMA(30, this.data);
      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption(option);

      this.myChart.on('dataZoom', function(event) {
        var batch = event.batch;
        if (batch[0].type === 'datazoom') {
          var startPercent = batch[0].start;
          var endPercent = batch[0].end;
          console.log(startPercent, endPercent);
          bus.$emit('datazoom', { name: '', startPercent, endPercent });
        }
      });
    },

    reInitChart() {
      console.log('reInitChart');
      // myChart.setOption(this.optsEcharts);

      if (this.myChart) {
        console.log(true);
        this.myChart.resize();
      }
    },
  },
  beforeCreate: function() {},
  created: function() {},
  beforeMount: function() {},
  mounted: function() {
    console.log('在实例挂载到DOM节点上之后');
    this.test();
    // this.init();
    // this.initChart();
    bus.$on('resizeWindow', () => {
      this.reInitChart();
      console.log('resizeWindow');
    });
  },
  beforeUpdate: function() {},
  updated: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.chart {
  height: 100%;
  width: 100%;
}
</style>
